package com.yboot.starter.mybatis.core.handle;

import com.yboot.starter.common.core.security.SecurityUserVO;
import com.yboot.starter.common.core.security.UserContext;
import com.yboot.starter.mybatis.config.BaseColumnProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Optional;

public class BaseEntityInnerMetaObjectHandler implements InnerMetaObjectHandler, InitializingBean {
    private final String createIdColumn;
    private final String updateIdColumn;
    private final String createTimeColumn;
    private final String updateTimeColumn;
    private final UserContext userContext;

    public BaseEntityInnerMetaObjectHandler(BaseColumnProperties baseColumnProperties, UserContext userContext) {
        this.createIdColumn = baseColumnProperties.getCreateIdColumn();
        this.updateIdColumn = baseColumnProperties.getUpdateIdColumn();
        this.createTimeColumn = baseColumnProperties.getCreateTimeColumn();
        this.updateTimeColumn = baseColumnProperties.getUpdateTimeColumn();
        this.userContext = userContext;
    }

    @Override
    public Object getFieldValue(String columnName) {
        if (!StringUtils.hasLength(columnName)) {
            return null;
        } else if (this.createTimeColumn.equals(columnName) || this.updateTimeColumn.equals(columnName)) {
            return LocalDateTime.now();
        } else {
            SecurityUserVO loginUser = userContext.getUser().orElse(new SecurityUserVO("system"));
            return loginUser.getUsername();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (!StringUtils.hasLength(this.createIdColumn)) {
            throw new RuntimeException("列名 createIdColumn 不能为空");
        } else if (!StringUtils.hasLength(this.updateIdColumn)) {
            throw new RuntimeException("列名 updateIdColumn 不能为空");
        } else if (!StringUtils.hasLength(this.createTimeColumn)) {
            throw new RuntimeException("列名 createTimeColumn 不能为空");
        } else if (!StringUtils.hasLength(this.updateTimeColumn)) {
            throw new RuntimeException("列名 updateTimeColumn 不能为空");
        }
    }
}